/**
 * 
 */
package de.farbstreich.tozen2.common;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.SocketException;

import com.sun.org.apache.xerces.internal.impl.xpath.regex.ParseException;

/**
 * @author Martin Spielmann (2008055519)
 *
 */
public class TozenMessageReaderWriter {
	BufferedReader br;
	BufferedWriter bw;
	
	public TozenMessageReaderWriter(InputStream in, OutputStream out){
		br = new BufferedReader(new InputStreamReader(in));
		bw = new BufferedWriter(new OutputStreamWriter(out));
	}
	
	public TozenProtocolMessage receive() throws SocketException, EndOfTheStreamException, IOException{
		
		String msgLine;
		while ((msgLine = br.readLine()) != null) {
				try {
					if (! msgLine.isEmpty())
						return new TozenProtocolMessage(msgLine);
				} catch (ParseException pe) {
					System.out.println("Ungültige Abfrage an Position " + pe.getLocation());
					System.out.println(pe);
				}
		}
		throw new EndOfTheStreamException();
	}
	
	public void send(TozenProtocolMessage msg) {
		try {
			bw.write(msg.toString());
			System.out.println("outgoing \"" + msg.type+ "\" message:" + msg.toString());
			bw.newLine();
			bw.flush();
		} catch (IOException e) {
			System.out.println("Beim senden der Nachricht ist ein Fehler aufgetreten");
			System.out.println(e);
		}
		
	}
	

}
